#!/bin/sh

# this script can be used by values that can have a default value by board

KEY=
CONFFILE=
SYSCONFFILE="/usr/share/batocera/sysconfigs/batocera.conf"

while test $# -ne 0
do
    case "${1}" in
	"-f")
	    shift
	    CONFFILE="${1}"
	    shift
	    ;;
	*)
	    KEY="${1}"
	    shift
    esac
done

# prefer the user value
if [ -n "${CONFFILE}" ]; then
    VALUE="$(/usr/bin/batocera-settings-get -f "${CONFFILE}" "${KEY}")"
else
    VALUE="$(/usr/bin/batocera-settings-get "${KEY}")"
fi
# when value is auto, ignore
if [ "$?" = 0 -a "${VALUE}" != "auto" ]; then
    echo "${VALUE}"
    exit 0
fi

if [ -f /sys/firmware/devicetree/base/model ]; then
    IFS= read -r BOARD_MODEL </sys/firmware/devicetree/base/model
fi
if [ -z "${BOARD_MODEL}" -a -f /sys/devices/virtual/dmi/id/product_name ]; then
    # give an other chance with dmi
    IFS= read -r BOARD_MODEL </sys/devices/virtual/dmi/id/product_name
fi
BOARD_MODEL="$(echo "$BOARD_MODEL" | sed -e s+"[^A-Za-z0-9]"+"_"+g)"
# fall back to board name if product name is not ideal
if [ -z "${BOARD_MODEL}" ] || [ "${BOARD_MODEL}" = "Default_string" ]; then
    BOARD_MODEL=$(cat /sys/devices/virtual/dmi/id/board_name 2>/dev/null | tr -d '\0' | sed -e s+"[^A-Za-z0-9]"+"_"+g)
fi

# prefer the board value
if [ -e "${SYSCONFFILE}.${BOARD_MODEL}" ]; then
    VALUE="$(/usr/bin/batocera-settings-get -f "${SYSCONFFILE}.${BOARD_MODEL}" "${KEY}")"
    # when value is auto, ignore
    if [ "$?" = 0 -a "${VALUE}" != "auto" ]; then
        echo "${VALUE}"
        exit 0
    fi
fi

# prefer the general value
if [ -e "${SYSCONFFILE}" ]; then
    /usr/bin/batocera-settings-get -f "${SYSCONFFILE}" "${KEY}" && exit 0
fi

exit 1
